<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta HTTP-EQUIV="pragma" CONTENT="no-cache">
    <meta HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate">
    <meta HTTP-EQUIV="expires" CONTENT="0">
    <title>学生信息管理</title>
    <link rel="stylesheet" type="text/css" th:href="@{/css/element.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/css/base.css}">
</head>
<style>
    .up-file input {
        position: absolute;
        font-size: 100px;
        right: 0;
        top: 0;
        opacity: 0;
        filter: alpha(opacity=0);
        cursor: pointer;
    }
    .el-message--error{
        word-break: break-word;
        word-wrap: break-word;
        white-space: -moz-pre-wrap;
        white-space: -hp-pre-wrap;
        white-space: -o-pre-wrap;
        white-space: -pre-wrap;
        white-space: pre;
        white-space: pre-wrap;
        white-space: pre-line;
    }
    .messageClass{
        z-index: 3000 !important;
    }
</style>
<body>
<div id="wrapper" v-cloak>
    <div style="margin-bottom: 10px;">
        <el-select v-model="selectedMajor" @change="handleMajorChange" filterable clearable size="small" placeholder="请选择专业" >
            <el-option v-for="major in selectMajors" :key="major" :label="major" :value="major"></el-option>
        </el-select>
        <el-select v-model="selectedClass" filterable clearable size="small" placeholder="请选择班级" >
            <el-option v-for="cls in selectClasses[selectedIndex]" :key="cls" :label="cls" :value="cls"></el-option>
        </el-select>
        <el-input size="small"   v-model="search" style="width:15%;" clearable
                  suffix-icon="el-icon-search" placeholder="请输入学号/姓名"></el-input>
        <el-button size="small" type="primary" @click.prevent="queryStudentInfo('message')">查询</el-button>
        <el-button size="small" type="primary" @click.prevent="edit">新增</el-button>
        <el-button size="mini" type="primary" @click="sedialogFormVisible = true,batchAddDataMessage()">批量添加</el-button>
        <!--<el-button size="mini" @click="handleBatchdelete" type="danger">批量删除</el-button>-->
        <el-label style="color:#919191;display: block;margin-top: 10px;"><b>班级毕业3个月后自动在系统中忽略</b></el-label>
    </div>

    <el-dialog title="上传文件" :visible.sync="sedialogFormVisible" width="40%" height="110%"
               v-loading="loadingStuInfo" :element-loading-text="loadingStuInfoText"
               :lock-scroll="true" :close-on-click-modal="false" :close-on-press-escape="false" >
        <el-row>
            <el-col :span="24">
                <el-form>
                    <!--ref="upLoad"-->
                    <el-upload class="upload-demo" ref="upload" multiple accept=".xls" action="" :auto-upload="false"
                               :show-file-list="true" :on-success="endUpload"
                               :on-error="errorUp"   :limit="1" :before-upload="beforeUpload"
                               :file-list="fileList"
                               :http-request="uploadFile">
                        <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
                        <div slot="tip">请上传文件大小不超过2MB,格式为 .xls类型的文件</div>
                    </el-upload>
                </el-form>
            </el-col>
        </el-row>
        <el-row style="margin-top: 20px;">
            <el-col :span="24">
                <el-button type="primary" size="small" style="margin-right: 2px;">
                    <a href="../student/downLoadTemplate" style="color: white; display: block;">下载模板</a>
                </el-button>
            </el-col>
        </el-row>
        <el-label style="color: red">批量添加请在左侧下载模板并通过模板上传</el-label>
        <div slot="footer" class="dialog-footer" style="text-align: center">
            <el-button style="margin-left:5px;" size="small" type="primary" @click="cancel()">取消上传</el-button>
            <el-button style="margin-left:22px;" size="small" type="primary" @click="submitUploadList">确定上传</el-button>
        </div>
    </el-dialog>

    <el-table :data="tableData" @selection-change="handleSelectionChange" v-loading="loading" border style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column width="90" prop="id" label="序号"></el-table-column>
        <el-table-column prop="stuid" label="学号"></el-table-column>
        <el-table-column prop="sname" label="姓名"></el-table-column>
        <el-table-column width="100" prop="ssex" label="性别"></el-table-column>
        <el-table-column prop="sphone" label="手机号码"></el-table-column>
        <el-table-column prop="classInfo.cname" label="班级名"></el-table-column>
        <el-table-column prop="spare" label="班长或学委">

            <template slot-scope="scope" >
                <!--<div v-if="scope.row.spare == 1">
                    <span style="color: #1c6ca1; font-weight: bolder">班长</span>
                    <el-popconfirm  @onConfirm="appoint(scope.row,0)" width="170" title="确定撤职吗?">
                    <el-button size="mini" type="danger" slot="reference" >撤职</el-button>
                    </el-popconfirm>
                </div>-->
                <div v-if="scope.row.spare >=1">
                    <span style="color: #2dc26b; font-weight: bolder">班委</span>
                    <el-popconfirm @onConfirm="appoint(scope.row,0)" width="170" title="确定撤职吗?">
                     <el-button size="mini" type="danger" slot="reference" >撤职</el-button>
                    </el-popconfirm>
                </div>
                <div v-else>
                    <el-popover :ref="scope.$index" placement="top" width="170">
                        <div style="margin: 0">
                            <p style="display: inline-block;">任命班委</p>
                            <el-button size="mini" type="success" @click="appoint(scope.row,2);scope._self.$refs[scope.$index].doClose();">班 委</el-button>
                            <!-- <el-button type="primary" size="mini" @click="appoint(scope.row,1);scope._self.$refs[scope.$index].doClose();">班长</el-button>-->
                        </div>
                        <el-button size="mini" slot="reference">委 任</el-button>
                    </el-popover>
                </div>
            </template>


        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
            <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="edit(scope.row)">修改</el-button>
                <el-popconfirm @onConfirm="del(scope.row.id)" title="确定删除？">
                    <el-button size="mini" type="danger" slot="reference">删除</el-button>
                </el-popconfirm>
                <el-popconfirm @onConfirm="resetPassword(scope.row.id, scope.row.stuid)" title="确定重置密码？">
                    <el-button size="mini" type="warning" slot="reference">重置密码</el-button>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div style="background-color: white; padding: 10px 0;text-align: right">
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="pageNum"
                :page-sizes="pageSizes"
                :page-size.sync="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                background
                :total="total">
        </el-pagination>
    </div>

    <el-dialog title="添加/修改学生信息" :visible.sync="dialogFormVisible" width="460px"
               :lock-scroll="true" :close-on-click-modal="false"
               :close-on-press-escape="false"  @close="resetForm('stuRef')">
        <el-form :model="studentEdit" ref="stuRef" :rules="stuRule">
            <el-form-item label="学号"  prop="stuid" label-width="100px">
                <el-input v-model="studentEdit.stuid" placeholder="请输入学号" autocomplete="off" style="width: 80%"></el-input>
            </el-form-item>
            <el-form-item label="姓名"  prop="sname" label-width="100px">
                <el-input v-model="studentEdit.sname" placeholder="请输入姓名" autocomplete="off" style="width: 80%"></el-input>
            </el-form-item>
            <el-form-item label="性别"  prop="ssex" label-width="100px">
                <el-input v-model="studentEdit.ssex" placeholder="请输入性别" autocomplete="off" style="width: 80%"></el-input>
            </el-form-item>
            <el-form-item label="手机号码"  prop="sphone" label-width="100px">
                <el-input v-model="studentEdit.sphone" placeholder="请输入手机号码" autocomplete="off" style="width: 80%"></el-input>
            </el-form-item>
            <el-form-item label="班级"  prop="cname" label-width="100px">
                <el-select v-model="studentEdit.cname" filterable size="small" placeholder="请选择班级,可输入"  style="width: 80%;">
                    <el-option v-for="(value,key) in classes" :key="value" :label="value" :value="value"></el-option>
                </el-select>
            </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="small" @click="cancel()">取 消</el-button>
            <el-button size="small" type="primary" @click="save('stuRef')">确 定</el-button>
        </div>
    </el-dialog>


</div>
<script type="text/javascript" th:src="@{/js/jquery.min.js}"></script>
<script type="text/javascript" th:src="@{/js/vue.min.js}"></script>
<script type="text/javascript" th:src="@{/js/axios.js}"></script>
<script type="text/javascript" th:src="@{/js/element.js}"></script>
<script type="text/javascript" th:src="@{/js/tinymce/tinymce.min.js}"></script>
<script type="text/javascript" th:src="@{/js/ycUpload.js}"></script>
<script>
    var savaBtn = true;
    let urlBase = "/api/user/";
    var v = new Vue({
        el:"#wrapper",
        data:{
            // 新增 修改 数据校验
            var: checkSphone = (rule, value, callback) => {
                if (!value) {
                    callback()
                }else {
                    const regCN = /^(?:(?:\+|00)86)?1\d{10}$/;
                    if (!regCN.test(value)) {
                        callback(new Error('手机号格式不正确'))
                    } else {
                        callback()
                    }
                }
            },
            var: checkSname = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('姓名不能为空'))
                }else {
                    const regCN = /^[\u4e00-\u9fa5]+|[a-zA-Z][A-Za-z\s]*[a-zA-Z]*|[a-zA-Z]+$/;
                    if (!regCN.test(value)) {
                        callback(new Error('姓名只能为中英文(英文用空格分开)'))
                    } else {
                        callback()
                    }
                }
            },
            var: checkStuId = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('学号不能为空'))
                }else {
                    const regCN = /^[0-9]{11}$/
                    if (!regCN.test(value)) {
                        callback(new Error('学号只能为11位数字'))
                    } else {
                        callback()
                    }
                }
            },
            var: checkCname = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请输入班级'))
                }else {
                    const regCN = /\p{Unified_Ideograph}+[0-9]{4}/u;
                    if (!regCN.test(value)) {
                        callback(new Error('班级格式不正确，请输入如网络1901'))
                    } else {
                        callback()
                    }
                }
            },
            var: checkSsex = (rule, value, callback) => {

                if (!value) {
                    callback(new Error('请输入性别'))
                }else{
                    if (value == "男" || value == "女") {
                        callback();
                    }else {
                        callback(new Error('请输入”男“或”女“'))
                    }
                }
            },
            // 弹窗
            visible: false,
            sedialogFormVisible: false,
            dialogFormVisible: false,
            // 页面加载效果
            loading: true,
            loadingStuInfo:false,//上传加载效果
            loadingStuInfoText:'拼命处理中请稍后',
            // 学生数据
            tableData: [],
            // 分页信息
            pageNum: 1,
            pageSize: 10,
            pageSizes: [10, 20, 30, 40],
            // 查询出的全部学生
            total: 0,
            // 全部班级
            classes: [],
            // 根据学号或姓名搜索
            search:"",
            //表单内容
            studentEdit:{
                cname: null,
                sname: null,
                stuid: null,
                sphone: null,
                ssex: null
            },
            // 用来判断页码是否归1
            flag: 0,
            //表单校验规则的绑定
            stuRule: {
                stuid : [
                    {validator: checkStuId, trigger: 'blur'}
                ],
                sname: [
                    {validator: checkSname, trigger: 'blur'}
                ],
                sphone: [
                    {validator: checkSphone, trigger: 'blur'}
                ],
                cname: [
                    {validator: checkCname, trigger: 'blur'}
                ],
                ssex: [
                    {validator: checkSsex, trigger: 'blur'}
                ]
            },
            selectionIds: "",   //批量删除选中,
            selectedMajor: "",  // 被选中的专业
            selectedClass: "",  // 被选中的学生
            selectMajors: [],   // 所有专业
            selectClasses: [],  // 所有班级
            // 0 添加 1 修改
            status: 0,
            fileList: [], // 文件列表
            // 前一次搜索
            preSelectedMajor: "",
            preSelectedClass: "",
            selectedIndex: 0
        },
        created(){
          // 查询
          this.queryStudentInfo();
          this.queryCname();
        },
        methods:{
            // 查询学生信息
            queryStudentInfo(message){
                // 判断是否为学号
                if (this.search.match(/\d{11}/)){
                    this.studentEdit.stuid = this.search.trim();
                }else if (this.search.match(/^\D+/)){
                    this.studentEdit.sname = this.search.trim();
                }
                // 筛选条件
                this.studentEdit.cname = this.selectedMajor != null ? this.selectedMajor : '';
                if (this.selectedClass != null){
                    this.studentEdit.cname += this.selectedClass;
                }
                this.studentEdit.cname = this.studentEdit.cname == "" ? null : this.studentEdit.cname;
                // 根据查询框重置页码
                if ((this.studentEdit.cname != null && this.studentEdit.cname.length > 0) || this.search != ""){
                    if (this.flag == 0){
                        this.pageNum = 1;
                        this.flag = 1;
                    }
                }else {
                    this.flag = 0;
                }
                if (this.selectedClass != this.preSelectedClass || this.selectedMajor != this.preSelectedMajor){
                    this.pageNum = 1;
                    this.preSelectedClass = this.selectedClass;
                    this.preSelectedMajor = this.selectedMajor;
                }
                axios({
                    url: `../student/query/${this.pageNum}/${this.pageSize}`,
                    method: 'post',
                    data : this.studentEdit,
                    header:{
                        'Content-Type':'application/json'
                    }
                }).then(res=>{
                    // 查询成功
                    if (res.data.code == 1){
                        this.tableData = res.data.data.data;
                        this.total = res.data.data.total;
                        this.tableData.forEach(item=>{
                            if (item.ssex == 1){
                                item.ssex = "男"
                            }else if (item.ssex == 0){
                                item.ssex = "女";
                            }
                        })
                        // 恢复初值
                        this.studentEdit.sname = null;
                        this.studentEdit.stuid = null
                        this.search = '';
                        if (message == 'message'){
                            this.$message({type: 'success', message: '查询成功'});
                        }
                    }else {
                        this.pageNum = 1;
                        if (this.pageNum != 1){
                            this.queryStudentInfo();
                        }else{
                            this.$message(res.data.msg);
                        }
                    }
                })
                this.loading = false;
            },
            // 查询所有的班级
            queryCname(){
                axios.get("../classInfo/query").then(res=>{
                    if (res.data.code == 1){
                        for(key in res.data.data){
                            this.classes.push(key)
                        }
                        this.selectClasses[0] = []
                        for (cls in this.classes){
                            this.selectMajors.push(this.classes[cls].substring(0, 2));
                            this.selectClasses[0].push(this.classes[cls].substring(2, 6));
                            if (this.selectClasses[this.classes[cls].substring(0, 2)] == null){
                                this.selectClasses[this.classes[cls].substring(0, 2)] = []
                            }
                            this.selectClasses[this.classes[cls].substring(0, 2)].push(this.classes[cls].substring(2, 6))
                        }

                        // 过滤重复的班级
                        this.selectMajors = this.selectMajors.filter((item, index, arr) => arr.indexOf(item, 0) === index)
                        for (let key in this.selectClasses) {
                            this.selectClasses[key] = this.selectClasses[key].filter((item, index, arr) => arr.indexOf(item, 0) === index)
                            this.selectClasses[key].sort()
                        }
                    }else{
                        this.$message(res.data.msg);
                    }
                })
            },
            // 选择全部修改为空
            handleMajorChange(){
                this.selectedClass = null;
                if (this.selectedMajor == '全部'){
                    this.selectedMajor = null;
                    this.selectedIndex = 0;
                }else {
                    this.selectedIndex = this.selectedMajor;
                }
            },
            // 批量选中
            handleSelectionChange(val){
                //记录选中
                let _this = this;
                let ids = "";
                _this.selectionIds = null;
                this.selectionIds = val;
            },
            // 批量删除
            handleBatchdelete(){
                //批量删除
                this.$confirm(`是否删除学生信息?`, '提示',
                    {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}).then(() => {
                    let params = new URLSearchParams();
                    let ids = [];
                    this.selectionIds.forEach(item=>{
                        ids.push(item.id);
                    })
                    params.append("ids",ids);
                    return axios.post("../student/deletes", params).then(response => {
                        if (response.data.code == "1") {
                            this.$message({type: 'success', message: '删除成功!'});
                            this.queryStudentInfo();
                        }else{
                            this.$message.error(response.msg);
                        }
                    });
                }).catch(() => {
                    this.$message({type: 'info', message: '已取消'});
                });
            },
            // 打开编辑学生信息弹窗
            edit(ref){
                // 打开弹窗前重置 学生信息
                this.studentEdit = {
                        cname: null,
                        sname: null,
                        stuid: null,
                        sphone: null,
                        ssex: null
                }
                // 根据id是否有无判断是修改还是 新增
                if (ref.id != null){
                    this.studentEdit.id = ref.id;
                    this.studentEdit.cid = ref.cid;
                    this.studentEdit.cname = ref.classInfo.cname;
                    this.studentEdit.sname = ref.sname;
                    this.studentEdit.sphone = ref.sphone;
                    this.studentEdit.ssex = ref.ssex;
                    this.studentEdit.stuid = ref.stuid;
                }
                this.dialogFormVisible = true
            },
            // 删除单个学生
            del(id){
                axios.delete(`../student/delete/${id}`).then(res=>{
                    if (res.data.code == 1){
                        this.$message(res.data.msg);
                        this.queryStudentInfo();
                    }else {
                        this.$alert(res.data.msg);
                    }
                })
            },
            // 添加/修改学生信息
            save(formName){
                this.$refs[formName].validate(valid => {//校检表单
                    if (valid) {
                            this.studentEdit.ssex = (this.studentEdit.ssex == "男" ? 1 : 0);
                            if (this.studentEdit.id != null) {
                                axios({
                                    url: `../student/modify/${this.studentEdit.id}`,
                                    method: "put",
                                    data: this.studentEdit,
                                    header: {
                                        'Content-Type': 'application/json'
                                    }
                                }).then(res => {
                                    if (res.data.code == 1) {
                                        this.$message({type: 'success', message: '修改成功!'});
                                        this.dialogFormVisible = false;
                                        this.studentEdit = {
                                            cname: null,
                                            sname: null,
                                            stuid: null,
                                            sphone: null,
                                            ssex: null
                                        };
                                    } else {
                                        this.$alert(res.data.msg);
                                        this.studentEdit.ssex = (this.studentEdit.ssex == "1" ? "男" : "女");
                                    }
                                    this.queryStudentInfo()
                                })
                            } else {
                                axios({
                                    url: `../student/add`,
                                    method: "post",
                                    data: this.studentEdit,
                                    header: {
                                        'Content-Type': 'application/json'
                                    }
                                }).then(res => {
                                    if (res.data.code == 1) {
                                        this.$message({type: 'success', message: '添加成功!'})
                                        this.dialogFormVisible = false;
                                        this.studentEdit = {
                                            cname: null,
                                            sname: null,
                                            stuid: null,
                                            sphone: null,
                                            ssex: null
                                        };
                                        this.queryStudentInfo()
                                    } else {
                                        this.$alert(res.data.msg);
                                        this.studentEdit.ssex = (this.studentEdit.ssex == "1" ? "男" : "女");
                                    }
                                });
                            }

                    }
                })
            },
            // 修改一次分页查询的个数
            handleSizeChange(){
                this.queryStudentInfo();
            },
            // 修改当前页更新数据
            handleCurrentChange(){
                this.queryStudentInfo();
            },
            // 重置表单信息
            resetForm(formName) {
                this.$refs[formName].resetFields();
                this.studentEdit = {
                        cname: null,
                        sname: null,
                        stuid: null,
                        sphone: null,
                        ssex: null
                }
            },
            // 任职 班长 或 学委
            appoint(row, spare){
                let params = new URLSearchParams();
                axios.put(`../student/update/${row.id}/${row.cid}/${spare}`).then(res=>{
                    if (res.data.code == 1){
                        if (spare != 0){
                            this.$message({type: 'success', message: '委任成功!'});
                        }else{
                            this.$message({type: 'warning', message: '撤职成功!'})
                        }
                        this.queryStudentInfo()
                    }else {
                        this.$alert(res.data.msg);
                    }
                })
                this.visible = false;
            },
            // 取消编辑
            cancel(){
                this.dialogFormVisible=false
            },
            // 上传文件
            async uploadFile(param){
                const File = param.file;
                const service = axios.create({})
                let formData = new FormData()
                formData.append("file", File);
                const res = await service({
                    url: '../student/file/upload',
                    method: 'POST',
                    transformRequest: [function(data, headers) {
                        // 去除post请求默认的Content-Type
                        delete headers.post['Content-Type']
                        return data
                    }],
                    data: formData
                }).then(res=>{
                    if (res.data.code== 1){
                        this.queryStudentInfo();
                        this.sedialogFormVisible = false;
                        this.loadingStuInfo = false;
                        this.$message({message: '上传成功', type: "success"});
                        this.$refs.upload.clearFiles ()
                    }else{
                        this.queryStudentInfo();
                        this.loadingStuInfo = false;
                        this.sedialogFormVisible = false;
                        this.$message({showClose: true,duration:0,message: res.data.msg, type: "error"});
                        this.$refs.upload.clearFiles ()
                    }
                })
            },
            // 进行上传前判断文件类型
            beforeUpload: function (file) {
                if (['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].indexOf(file.type) == -1 && ['application/vnd.ms-excel'].indexOf(file.type) == -1) {
                    this.$message.error({message: "请上传.xls的文件", type: 'error'});
                    return false;
                }
            },
            // 上传异常
            errorUp(err) {
                this.$message({message: err, type: "error"})
            },
            // 上传结束
            endUpload() {
                this.queryStudentInfo()
            },
            // 确认上传
            submitUploadList() {
                const files = this.$refs.upload.uploadFiles;
                if (files[0] == null){
                    this.$message({message: "请选择文件后再点确定", type: "warning"});
                    return false;
                }
                let size2M = (files[0].size / 1024 / 1024) < 2;
                if(!size2M){
                    this.$message.warning('上传大小不能超过2M!');
                    return false;
                }
                if (files >= 0) {
                    this.$message({message: "请选择文件后再点确定", type: "warning"});
                } else {
                    this.$message({message: "数据添加中请稍后!", type: "warning", duration: 3000});
                    this.loadingStuInfo = true;
                    this.$refs.upload.submit();
                }
            },
            resetPassword(id, stuid){
                axios.post(`../student/reset/${id}/${stuid}`).then(res=>{
                    if (res.data.code == 1){
                        this.$message(res.data.msg)
                    }else{
                        this.$alert(res.data.msg);
                    }
                })
            },batchAddDataMessage(){
                this.$message({
                    showClose: true,
                    message: '温馨提示: 在批量添加学生前,请先确认 辅导员 和 班级 在系统中是否存在,不存在请先添加相关数据!',
                    type: 'warning',
                    duration:10000,
                    customClass:"messageClass"
                });
            }
        }
    })

</script>
</body>
</html>
